<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 消息
 *
 */
class Message extends CI_Controller {
	
	function __construct()
	{
		parent::__construct();
		//加载usermodel
		$this->load->model('usermodel');
		$this->uid = $this->usermodel->get_id_by_token($this->input->post('token'));
		//加载messagesmodel
		$this->load->model('messagesmodel');
	}
	
	function index()
	{
		//默认
		$this->mymessages();
	}
	
	/**
	 * 我的消息列表
	 *
	 */
	function mymessages()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$messages = $this->messagesmodel->get_messages($this->uid);
		if(count($messages) > 0){
			//输出最终的xml
			echo $this->xmllib->get_xml($messages, array('message'), 'messages');
			exit;
		}else{
			//结果集为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 具体消息
	 *
	 * @param unknown_type $id
	 */
	function msg()
	{
		header('Content-type:text/xml');// 向浏览器输出 xml
		$id = $this->input->post('messageid');
		$message = $this->messagesmodel->get_message($id, $this->uid);

		if ($message) {
			/*if($message[0]['uid'] != $this->uid){
				//如果此消息不属于当前用户的
				echo $this->xmllib->error_xml('无此消息');
				exit;
			}*/
			//输出最终的xml
			echo $this->xmllib->get_xml($message, array('message'));
			exit;
		}else{
			//结果集为空
			echo $this->xmllib->empty_xml();
			exit;
		}
	}
	
	/**
	 * 添加留言信息
	 *
	 */
	function addmessage()
	{
		//此处 fanid = $this->uid
		header('Content-type:text/xml');// 向浏览器输出 xml
		//加载表单验证类库
  		$this->load->library('form_validation');
		$uid = $this->input->post('uid');
		//验证 uid, fanid
		if(empty($uid)){
			//留言接受者无效
			echo $this->xmllib->error_xml('留言失败，请重试');
			exit;
		}
		if($uid == $this->uid){
			echo $this->xmllib->error_xml('不能给自己留言哦');
			exit;
		}
		$_POST['msg'] = isset($_POST['msg']) ? $_POST['msg'] : '555';//此处设置时为了防止生成xml报错
		//字段验证设置
		$this->form_validation->set_rules('msg', '留言内容', 'trim|required|max_length[140]');
		$this->form_validation->set_message('required', '%s 不能为空');
		$this->form_validation->set_message('max_length', '%s 字数不能多于%d');
		$this->form_validation->set_error_delimiters('', '');
		if ($this->form_validation->run() == FALSE){
			echo $this->xmllib->error_xml(form_error('msg'));
			exit;
		}
		
		$msg = $this->input->post('msg');
		
		//检测要给留言的用户的有效性
		$this->load->model('usermodel');
		if(!$this->usermodel->check_user_by_id($uid)){
			//用户不存在
			echo $this->xmllib->error_xml('您要留言的用户不存在或无效');
			exit;
		}
		
		//发送留言信息哦
		//初始化数据
		$data = array('uid' 		=> $uid,
						'fanid'		=> $this->uid,
						'msg'		=> $msg);

		if($this->messagesmodel->insert_message($data)){
			//添加成功
			echo $this->xmllib->success_xml('您的留言发送成功');
			exit;
		}else{
			//失败
			echo $this->xmllib->error_xml('您的留言发送失败，请稍后再试');
			exit;
		}
	}
	
}

/* End of file message.php */
/* Location: ./application/controllers/message.php */